package org.chen.lister;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.chen.enu.TaskStatus;
import org.chen.mapper.CommentTaskMapper;
import org.chen.model.CommentTask;
import org.chen.model.RetryMessage;
import org.chen.service.impl.BatchStatsManager;
import org.chen.service.impl.CommentTaskExecutionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
@RocketMQMessageListener(
    topic = "comment_retry_topic",
    consumerGroup = "comment_retry_consumer"
)
public class RetryConsumer2 implements RocketMQListener<RetryMessage> {

    @Autowired
    private CommentTaskExecutionService commentTaskExecutionService;

    @Autowired
    private CommentTaskMapper taskMapper;

    @Autowired
    private BatchStatsManager batchStatsManager;

    @Value("${comment.max-retries:3}")
    private int maxRetries;
    
    @Override
    public void onMessage(RetryMessage message) {
        log.info("Consumer2接收到消息：{}",message);
        try {
            CommentTask task = taskMapper.selectById(message.getTaskId());
            if (task != null && TaskStatus.PENDING.name().equals(task.getStatus())) {
                if (message.getRetryCount() >= maxRetries) {
                    handleMaxRetriesExceeded(task);
                    return;
                }
                commentTaskExecutionService.attemptComment(task);
            }
        } catch (Exception e) {
            log.error("Retry processing error: {}", message.getTaskId(), e);
        }
    }

    private void handleMaxRetriesExceeded(CommentTask task) {
        try {
            // 1. 更新任务状态为最终失败
            task.setStatus(TaskStatus.FAILED.name());
            task.setErrorMessage("重试" + maxRetries + "次，也无法完成。");
            task.setUpdateTime(LocalDateTime.now());
            taskMapper.updateById(task);

            // 2. 更新批次进度
            batchStatsManager.updateBatchProgress(task.getBatchNo());

            // 3. 可以选择发送告警或通知
            log.warn("Task {} exceeded maximum retries", task.getId());

            // 4. 如果需要，可以将失败信息记录到专门的失败记录表
            // failureRecordMapper.insert(new FailureRecord(task));
        } catch (Exception e) {
            log.error("Error handling max retries exceeded for task {}", task.getId(), e);
        }
    }
}